<script lang="ts" setup>
import { h, ref } from 'vue'

import { useVbenModal } from '@vben/common-ui'

import { useDebounceFn } from '@vueuse/core'
import { Modal as AntModal, Button, Divider, message, Space, Spin } from 'ant-design-vue'
import dayjs from 'dayjs'

import { useVbenForm } from '#/adapter/form'
import { getSupplyList } from '#/api/common'
import { againstSupply, approvalSupply, creatSupply, delSupply, editSupply, getSupply } from '#/api/supply'

import product from '../modules/product.vue'
import purchaseModal from '../modules/purchaseModal.vue'
import {
  payOrderAdd,
  payOrderAgainst,
  payOrderApproval, payOrderDel,
  payOrderEdit,
  payOrderUpdate
} from "#/api/payOrder";

const emit = defineEmits(['refresh'])
const record_sn = ref(0)
const Posted = ref(0)

const inputDisabled = ref(true)
const keyword1 = ref('')
const fetching = ref(false)
/**
 * 获取简码远程选项
 */
async function fetchRemoteOptions({ keyword = '' }: Record<string, any>) {
  let quick_search = ''
  let initValue = ''
  const initKey = 'id'
  if (keyword.startsWith('initValue:')) {
    initValue = keyword.replace('initValue:', '')
    if (initValue) {
      initValue = keyword.replace('initValue:', '').split(',')
    }
  } else {
    quick_search = keyword
  }
  const { list } = await getSupplyList({
    quick_search,
    page: 1,
    limit: 999,
    initKey,
    initValue,
    select: true,
  })
  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }))
}


const [productModal, productModalApi] = useVbenModal({
  connectedComponent: product,
})

const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    componentProps: {
      class: 'w-4/5',
    },
  },
  layout: 'horizontal',
  schema: [
    {
      component: 'CustomRender',
      fieldName: '_divider',
      formItemClass: 'col-span-4',
      hideLabel: true,
    },

    {
      component: 'Input',
      fieldName: 'record_sn',

      label: '付款单号',
      componentProps: {
        disabled: true,
        placeholder: '后台自动生成',
      },
    },
    {
      component: 'DatePicker',
      fieldName: 'record_date',
      defaultValue: dayjs().format('YYYY-MM-DD'),
      label: '单据日期',
      rules: 'required',
      componentProps: {
        disabled: inputDisabled,
        type: 'date',
        clearable: true,

        placeholder: '请选择单据日期',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'Input',
      fieldName: 'Manualid',
      label: '手工单号',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入手工单号',
      },
    },
    {
      component: 'ApiSelect',
      // 对应组件的参数
      disabled: inputDisabled,
      componentProps: () => {
        return {

          api: fetchRemoteOptions,
          // 禁止本地过滤
          filterOption: false,
          notFoundContent: fetching.value ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword1.value = value
          }, 300),

          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword1.value || undefined,
          },
          showSearch: true,
          allowClear: true,
          immediate: false,
          alwaysLoad: true,
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            if (open) keyword1.value = ''
          },
        }
      },
      // 字段名
      fieldName: 'supply_id',
      // 界面显示的label
      label: '供应商',
      rules: 'required',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value ? h(Spin) : undefined,
        }
      },
    },
    {
      component: 'Input',
      fieldName: 'FkCategory',
      label: '类别',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入类别',
      },
    },
    {
      component: 'Input',
      fieldName: 'Planid',
      label: '生产制单',
      componentProps: {
        allowClear: true,
        disabled: inputDisabled,
        placeholder: '请输入选择生产制单',
        onClick: (value: any) => {
          productModalApi.open()
        },
      },
    },
    {
      component: 'Input',
      fieldName: 'Fkmode',
      label: '付款方式',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入付款方式',
      },
    },
    {
      component: 'Input',
      fieldName: 'Shoukuanren',
      label: '收款人',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入收款人',
      },
    },
    {
      component: 'Input',
      fieldName: 'Item',
      label: '项目',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入项目',
      },
    },
    {
      component: 'Input',
      fieldName: 'Amount',
      label: '调整金额',
      rules: 'required',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入金额',
      },
    },
    {
      component: 'Input',
      fieldName: 'AmountDj',
      label: '抵扣订金',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入抵扣订金',
      },
    },


    {
      component: 'Textarea',
      fieldName: 'Remark',
      label: '备注',
      formItemClass: 'col-span-4',
      componentProps: {
        disabled: inputDisabled,
        placeholder: '请输入备注',
      },
    },
  ],
  wrapperClass: 'grid-cols-4',
})
const rowid = ref(0)
const [Modal, modalApi] = useVbenModal({
  destroyOnClose: true,
  class: 'w-[95%] h-[100%]',
  appendToMain: true,
  fullscreenButton: false,
  onCancel() {
    modalApi.close()
    emit('refresh')
  },
  onConfirm: async () => {
    await baseFormApi.validateAndSubmitForm()
  },
  onOpenChange: async (isOpen: boolean) => {
    if (isOpen) {
      const { rowData, view } = modalApi.getData<Record<string, any>>()

      if (view === 'add') {
        inputDisabled.value = false
      } else if (view === 'edit') {
        inputDisabled.value = true
        rowid.value = rowData
        record_sn.value = rowData.record_sn
        initData()
      }
    }
  },
})

const shareData = (res: any) => {
  baseFormApi.setValues({ caigou_id: res.list[0].caigou_id }, false)
  baseFormApi.setValues({ Manualid: res.list[0].purchase_sn }, false)
}
const addProd = (res: any) => {
  baseFormApi.setValues({ Planid: res.production_sn }, false)
}

async function initData() {
  payOrderEdit({ record_sn: rowid.value.record_sn }).then((response) => {
    baseFormApi.setValues(response.row, false)
    Posted.value = response.row.Posted
    keyword1.value = `initValue:${response.row.supply_id}`
  })
}

// 审核
const handleApproval = async () => {
  try {
    const res = await payOrderApproval({ ids: [record_sn.value] })
    if (res.data.code !== 1) {
      message.error(res.data.msg)
      return
    }
    await initData()
    message.success(res.data.msg)
    emit('refresh')
  } catch {
    message.error('审核失败，请重试')
  }
}

// 反审
const handleAgainst = async () => {
  try {
    const res = await payOrderAgainst({ ids: [record_sn.value] })
    if (res.data.code !== 1) {
      message.error(res.data.msg)
      return
    }
    await initData()
    message.success(res.data.msg)
    emit('refresh')
  } catch {
    message.error('反审核失败，请重试')
  }
}

// 删除
const handleDel = async () => {
  AntModal.confirm({
    title: '确认删除',
    content: '确定要删除吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        const res = await payOrderDel({ ids: [record_sn.value] })
        if (res.data.code !== 1) {
          message.error(res.data.msg)
          return
        }
        message.success('删除成功')
        modalApi.close()
        emit('refresh')
      } catch {
        message.error('删除失败，请重试')
      }
    },
  })
}

// 修改
const changeToSave = () => {
  inputDisabled.value = false
}

// 保存
async function save() {
  const values = await baseFormApi.getValues()
  const parmas = {
    ...values,
    fktype:3
  }
  if (values.id) {
    payOrderUpdate(parmas).then((res: any) => {
      if (res.data.code === 1) {
        message.success(res.data.msg)
        modalApi.close()
        emit('refresh')
      } else {
        message.error(res.data.msg)
      }
    })
  } else {
    payOrderAdd(parmas).then((res: any) => {
      if (res.data.code === 1) {
        message.success(res.data.msg)
        modalApi.close()
        emit('refresh')
      } else {
        message.error(res.data.msg)
      }
    })
  }

  // 这里可以添加后续的保存逻辑
}
</script>

<template>
  <Modal :title="inputDisabled ? '编辑' : '新建'">
    <BaseForm>
      <template #_divider>
        <Divider orientation="left">基础信息</Divider>
      </template>
    </BaseForm>
    <template #footer>
      <div class="flex justify-end">
        <Space>
          <Button @click="modalApi.close()">取消</Button>
          <Button v-if="!inputDisabled" type="primary" @click="save()"> 保存 </Button>
          <Button v-if="Posted === 0 && inputDisabled" type="primary" danger @click="handleApproval"> 审核 </Button>
          <Button v-if="Posted > 0 && inputDisabled" type="primary" danger @click="handleAgainst"> 反审 </Button>
          <Button v-if="Posted === 0 && inputDisabled" type="primary" danger @click="handleDel"> 删除 </Button>
          <Button v-if="Posted === 0 && inputDisabled" type="primary" @click="changeToSave"> 修改 </Button>
        </Space>
      </div>
    </template>
  </Modal>
  <purchaseModalModal @share-data="shareData" />
  <productModal @push-data="addProd" />
</template>

<style scoped>
.fina-box {
  padding: 10px 0;
}
.fina-btn {
  margin-bottom: 16px;
}
</style>
